<?php

/**
 * Add a reservation_booking
  
* @param int $service_id
* @param int $week_num
* @param str $reserveDate
* @param str $reserveTime
* @param int $user_id
* @param int $postID
* @return boolean True on success, false on fail
 */
function web_apper_insert_reservation_booking( $service_id, $week_num, $reserveDate, $reserveTime, $user_id, $postID) {	
	$booking    				 = new WebApper\Booking\Booking;
	$booking->service_id		 = $service_id;
	$booking->week_num			 = $week_num;
	$booking->reserveDate		 = $reserveDate;
	$booking->reserveTime		 = $reserveTime;
	$booking->user_id			 = $user_id;
	$booking->postID		     = $postID;
	
	if ( $booking->save() )
		return true;

	return false;
}

/**
 * update a  reservation_booking
 * 
* @param int $service_id
* @param int $week_num
* @param str $reserveDate
* @param str $reserveTime
* @param int $user_id
* @param int $postID
* @return boolean True on success, false on fail
 */
function web_apper_update_reservation_booking( $service_id, $week_num, $reserveDate, $reserveTime, $user_id, $postID) {	
	$booking     			= new WebApper\Booking\Booking($booking_id);
	$booking->service_id	= $service_id;
	$booking->week_num		= $week_num;
	$booking->reserveDate	= $reserveDate;
	$booking->reserveTime	= $reserveTime;
	$booking->user_id		= $user_id;
	$booking->postID		= $postID;
	
	if ( $booking->save() )
		return true;

	return false;
}

/**
 * add filter 
 * 
* @param array $atts
* @return shortcode attribute array
 */

function add_required_fields( $atts ) {
	if ( !empty( $atts['include'] ) )
		$atts['include'] .= ',';
		$atts['include'] .= 'first-name,last-name,email-primary,phone-primary,booking-timestamp';
	return $atts;
}

/**
* add action 
* 
* @param int $postID
* @param array $submitted_values
* @return boolean True on success, false on fail
 */
function get_form_values( $postID, $submitted_values ) {
		global $wp_roles;
		$objBooking	= new WebApper\Booking\Booking($booking_id);		
		$bookingTimeArray = explode(",",$_POST['booking-timestamp']);
		$serviceId	= $bookingTimeArray[0];
		$wek_num	= $bookingTimeArray[1];
		$bookingDate = $bookingTimeArray[2];
		$bookingTime = $bookingTimeArray[3];
		$staffUserId = array();
		$obService = web_apper_populate_service($serviceId);
		$serviceCap = $obService->capability; // GET THE SERVICE CAPABILITY
		
    	$roles = $wp_roles->get_names(); //GET THE ALL ROLE
		foreach($roles as $role=>$roleVal)
		{
			$roleCapability = get_role($role); //			
			$roleCapabilityArry = $roleCapability->capabilities; //GET ALL ACTIVE CAPABILTY BY ROLE
			foreach($roleCapabilityArry as $key => $val )
			{
				if( $key == $serviceCap)
				{
					$blogusers = get_users("blog_id=1&orderby=nicename&role=".$role."");		
					foreach ($blogusers as $user){
						$staffUserId[] = $user->ID;
					}
				}
			}
		}
				
		$bookedStaffId = array();
		$objBooking->service_id = $serviceId;
		$objBooking->reserveDate = $bookingDate;
		$objBooking->week_num = $wek_num;
		$rows = $objBooking->get_booking_user_id();
		foreach($rows as $row){
			$bookedStaffId[] = $row->user_id;
		}
		$excludeStatff = array_merge(array_diff($staffUserId, $bookedStaffId), array_diff($bookedStaffId, $staffUserId));
		if(count($excludeStatff)>0){
			shuffle($excludeStatff);
			$staffId = $excludeStatff[0];
		}
		else
		{
			$latestBooking = array();
			foreach($rows as $row){	
				$objBooking->user_id = $row->user_id;		
				$lastestDateTimes = $objBooking->get_creation_date_by_user_id();			
				foreach($lastestDateTimes as $lastestDateTime){
					$latestBooking[] = $lastestDateTime->creation_date;
				}				
			}			
			$minTime = min($latestBooking);			
			$staffIds = $objBooking->get_user_id_by_fast_booking_date($minTime);
			$staffId = $staffIds[0]['user_id'];			
		}
		$meta_values = get_post_meta( $postID);
		$user_info = get_userdata($staffId);
		$clientEmail = $meta_values['email-primary'][0];
		$staffEmail = $user_info->user_email;
		$result = web_apper_insert_reservation_booking($serviceId, $wek_num, $bookingDate, $bookingTime, $staffId, $postID);
		if ( $result ) {
			$objServices = web_apper_populate_service($serviceId);
			$autoConf = $objServices->autoconfirm ==1 ? true: false;
			$clientConfirmMailContent		= email_message_fomatting($serviceId, $postID, $staffId, $bookingDate, $bookingTime, $objServices->client_confirm_email, $autoConf);
			$clientAutoConfirmMailContent	= email_message_fomatting($serviceId, $postID, $staffId, $bookingDate, $bookingTime, $objServices->client_autoconfirm_email, $autoConf);
			$clientCancellationMailContent	= email_message_fomatting($serviceId, $postID, $staffId, $bookingDate, $bookingTime, $objServices->client_cancelation_email, false);
			$staffConfirmMailContent		= email_message_fomatting($serviceId, $postID, $staffId, $bookingDate, $bookingTime, $objServices->agent_confirm_email, false);
			$staffCancellationMailContent	= email_message_fomatting($serviceId, $postID, $staffId, $bookingDate, $bookingTime, $objServices->agent_cancelation_email, false);
			$adminConfirmMailContent		= email_message_fomatting($serviceId, $postID, $staffId, $bookingDate, $bookingTime, $objServices->admin_confirm_email, false);
			$adminCancellationMailContent	= email_message_fomatting($serviceId, $postID, $staffId, $bookingDate, $bookingTime, $objServices->admin_cancelation_email, false);
			
			///Client Email
			$clientMessage = $autoConf ? $clientAutoConfirmMailContent : $clientConfirmMailContent;	
			//wp_mail( $clientEmail, 'Client Confirmation Email', $clientMessage, array('MIME-Version: 1.0','Content-type: text/html; charset=iso-8859-1',sprintf('From: %s','jesse@azrto.info'),sprintf( 'X-Mailer: PHP/%s', phpversion() )));
			
			$staffMessage = $staffConfirmMailContent;								
			//wp_mail( $staffEmail, 'Staff Confirmation Email', $staffMessage, array('MIME-Version: 1.0','Content-type: text/html; charset=iso-8859-1' ,sprintf('From: %s','jesse@azrto.info'),sprintf( 'X-Mailer: PHP/%s', phpversion() )));
			
			return true;
		}	
		return false;	
	}
	
	add_action( 'recordform_post_submit', 'get_form_values', 10, 2 );
	
/**
* Email Message Formatting
* @param int $serviceId
* @param int $postID
* @param int $staffId
* @param str $bookingDate
* @param str $bookingTime
* @param str $mail_content
* @param bool $isAutoConfirm
*/
function email_message_fomatting($serviceId, $postID, $staffId, $bookingDate, $bookingTime, $mail_content, $isAutoConfirm =false){
	$objServices = web_apper_populate_service($serviceId);
	$meta_values = get_post_meta( $postID);
	$user_values = get_userdata($staffId);
	$site_name = get_bloginfo('name');
	$service_name = $objServices->service_name; 
	$client_first_name = $meta_values['first-name'][0];
	$client_last_name = $meta_values['last-name'][0];
	$staff_name = $user_values->display_name;
	if($isAutoConfirm)
	{
		$confirmation_link = "Confirmation link here.";
	}
	else
	{
		$confirmation_link = "";
	}
	$start_time =   date('h:i a', strtotime($bookingTime));
	$end_time = date('h:i a', strtotime($bookingTime.'+'.$objServices->service_duration.' minutes'));
	$site_name = $current_site->site_name;
	$body_content = $mail_content;
	$body_content = str_replace("CLIENT_FIRST_NAME", $client_first_name, $body_content);
	$body_content = str_replace("CLIENT_LAST_NAME", $client_last_name, $body_content);
	$body_content = str_replace("SERVICE_NAME", $service_name, $body_content);
	$body_content = str_replace("STAFF_NAME", $staff_name, $body_content);
	$body_content = str_replace("BOOKING_DATE", $bookingDate, $body_content);
	$body_content = str_replace("START_TIME", $start_time, $body_content);
	$body_content = str_replace("END_TIME", $end_time, $body_content);
	$body_content = str_replace("CONFIRM_LINK", $confirmation_link, $body_content);
	$body_content = str_replace("SITE_NAME", $site_name, $body_content);
	return $body_content;	
}

?>